package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.entity.Setmeal;
import com.itheima.entity.SetmealDish;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    public void saveSetmeal(SetmealDto setmealDto) {
        //1. 添加套餐数据
        this.save(setmealDto);


        //2.添加套餐中的菜品列表
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();


        //3.设置套餐中每道菜的套餐id
        setmealDishes.stream().peek(setmealDish -> setmealDish.setSetmealId(setmealDto.getId())).collect(Collectors.toList());


        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void updateSetmeal(SetmealDto setmealDto) {
        //1.修改setmeal表
        this.updateById(setmealDto);
        //2.修改setmealdish表
        //2.1先删
        Long setmealId = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(SetmealDish::getSetmealId,setmealId);
        setmealDishService.remove(lqw);
        //2.2后新增
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes.stream().peek(setmealDish -> setmealDish.setSetmealId(setmealId)).collect(Collectors.toList());
        setmealDishService.saveBatch(setmealDishes);
    }
}
